<template>
  <div>
    <div class="box-card" v-for="(file, index) in files" :key="index">
      <div class="clearfix">
        <span>{{ file.name }}</span>
        &nbsp;&nbsp;&nbsp;&nbsp;
        <el-button @click="() => handleFileClick(file)" type="text">预览</el-button>
        <!-- <el-button @click="() => handleFileDownload(file)" type="text">下载</el-button> -->
      </div>
    </div>
  </div>
  <el-dialog
    v-model="previewVisible"
    :title="previewTitle"
    width="80%"
    height="92%"
    :before-close="handleClosePreview"
  >
    <div v-if="previewType === 'image'">
      <img :src="dialogFile?.url" alt="预览图片" class="w-80% ml-10%" />
    </div>
    <div v-if="previewType === 'pdf'">
      <iframe :src="dialogFile?.url" style="width: 100%; height: 80vh" frameborder="0"></iframe>
    </div>
    <div v-if="previewType === 'text'">
      <iframe :src="dialogFile?.url" style="width: 100%; height: 80vh" frameborder="0"></iframe>
    </div>
    <div v-if="previewType === 'other'">
      <p>无法预览此文件，您可以下载它。</p>
    </div>
  </el-dialog>
</template>

<script setup lang="tsx">
import { defineProps } from 'vue'

interface FileType {
  name: string
  url: string // 如果有其他属性，可以继续添加
}

const props = defineProps({
  files: {
    type: Array as () => FileType[], // 指定 files 的类型
    required: true
  }
})

// const emit = defineEmits(['file-click', 'file-download'])
const fileExtensions = {
  image: ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.svg'],
  pdf: ['.pdf'],
  text: ['.txt', '.html', '.md']
}

// 判断文件是否可以预览
const isPreviewable = (fileUrl: string) => {
  const extension = fileUrl.slice(fileUrl.lastIndexOf('.')).toLowerCase()

  if (fileExtensions.image.includes(extension)) {
    return 'image'
  }
  if (fileExtensions.pdf.includes(extension)) {
    return 'pdf'
  }
  if (fileExtensions.text.includes(extension)) {
    return 'text'
  }
  return 'other' // 无法预览的文件类型
}

const previewVisible = ref(false)
const previewTitle = ref('')
const previewType = ref('')
const dialogFile = ref({ id: 0, url: '', name: '' })

const handleFileClick = (fileParams) => {
  const type = isPreviewable(fileParams.url)
  if (type === 'other') {
    handleFileDownload(fileParams)
  } else {
    previewType.value = type
    previewTitle.value = fileParams.name
    previewVisible.value = true
    dialogFile.value.url = fileParams.url
  }
}

const handleFileDownload = async (fileParams) => {
  try {
    if (fileParams.url && fileParams.url.match(/\.(jpg|jpeg|png|gif|bmp)$/i)) {
      window.open(fileParams.url, '_blank')
    } else {
      const link = document.createElement('a')
      link.download = fileParams.name || 'download'
      link.href = fileParams.url
      link.target = '_blank'
      link.click()
    }
  } catch (error) {
    console.error('Error handling file download or open:', error)
  }
}

const handleClosePreview = () => {
  previewVisible.value = false
  previewType.value = ''
}
</script>

<style scoped>
.box-card {
  margin-bottom: 10px;
}
</style>
